import commands
import telnetlib
import os

class dtnmanager:
	host = "127.0.0.1"
	DTN_PORT = '5050'
	DTN_START = 'dtnd -c /usr/voyagedtn/dtn.conf -d -o /tmp/dtn.log'
	#DTN_BUNDLE_STATS = 'bundle list'
	DTN_PID = 'pidof dtnd'
	DTN_KILL = 'kill -9 '

	FIND_CHILD = "ps -o pid --noheaders --ppid "
	
	def __init__(self, host):
		self.host = host
	
	def dtn_isrunning(self):
		status,dtn_pid = commands.getstatusoutput(self.DTN_PID)
		#print "dtn status %s " %status
		
		if dtn_pid=='':
			return False
		else:
			return dtn_pid
			

	def start_dtn(self):
		dtn_pid = self.dtn_isrunning()
		if dtn_pid==False:
			try:
				#print "start DTN2 Daemon..."
				commands.getstatusoutput(self.DTN_START)
			except:
				return False
		else:
			return True
			
	def stop_dtn(self,processid):
		dtn_pid = self.dtn_isrunning()
		if dtn_pid==False:
			return True
		else:
			try:
				#print 'stop DTN2 daemon...'
				#print self.DTN_KILL + dtn_pid
				status,res = commands.getstatusoutput(self.DTN_KILL + dtn_pid)
				return True
				#sta,res = commands.getstatusoutput(self.DTN_KILL + str(processid))
				#"ps -o pid --ppid %d --noheaders" % parent_pid
				#stop child process
				#print self.FIND_CHILD + str(processid)
				#sta,res = commands.getstatusoutput(self.FIND_CHILD + str(processid))
				#print self.DTN_KILL + res.__getslice__(1,5)
				#sta,res = commands.getstatusoutput(self.DTN_KILL + res.__getslice__(1,5))
			except:
				return False
		return False
	
	def getTelentConnection(self):
		try:
			terminal = telnetlib.Telnet(self.host, self.DTN_PORT)
		except:
			return False
		return terminal

	def excute(self,cmd):
		terminal = self.getTelentConnection()
		if not terminal:
			return False
		else:
			try:
				#print cmd
				terminal.read_until("dtn%")
				terminal.write(cmd + "\n")
				results = terminal.read_until("% ")
				return results
			except:
				return False

'''
def start_dtn(self):
		dtn_pid = self.dtn_isrunning()
		if dtn_pid is None:
			try:
				#print "start DTN2 Daemon..."
				child_pid = os.fork()
				if child_pid == 0:
					commands.getstatusoutput(self.DTN_START)
			except:
				return False
		else:
			return True
'''


